<template>
	<view>
		<fa-navbar title="课程详情"></fa-navbar>
		<view class="content">
			<view class="video-play">
				<video v-if="videoType=='video'" ref="videoRef" id="myVideo" class="video" :src="videoUrl" @error="videoErrorCallback"
					enable-danmu :danmu-btn="false" :controls="false" :enable-progress-gesture="false" :poster="coverUrl"
					@timeupdate="handleTimeUpdate" @pause="handlePause" @loadedmetadata="handleLoadedMetadata"></video>
				<view v-else class="no-video" @click="openField(videoUrl)">
					<u-image width="702" height="395" radius="20" :src="coverUrl"></u-image>
					<view class="play">
						<u-icon name="play-right-fill" size="60" color="#ffffff"></u-icon>
					</view>
				</view>

			</view>
			<view class="tabs">
				<view class="it" v-for="(item,index) in list1" :class="activeIndex === index?'active':''" :key="index"
					@click="clickTabs(index)">
					<text :class="activeIndex === index?'ft30 fw6':'ft28'">{{item.name}}</text>
					<u-line class="u-line" :color="activeIndex === index?'#0052D9':'#F3F5F8'" length="30rpx"></u-line>
				</view>
			</view>
			<view v-if="activeIndex === 0">
				<view class="detail">
					<view class="detail1">
						<text class="major">{{courseDetail.major.name}}</text>
						<text class="name">{{courseDetail.name}}</text>
					</view>
					<view class="d-content">
						<view class="c-left">
							<text>{{courseDetail.watchednum}}人学过</text>
							<text></text>
						</view>
						<view class="c-right">
							<u-icon :name="!courseDetail.is_collect?'star':'star-fill'"
								:color="!courseDetail.is_collect?'#666666':'#F6C643'" size="32"
								@click="collect"></u-icon>
							<text class="like">收藏</text>
						</view>
					</view>
				</view>
				<view class="c-intro">
					<u-parse :content="courseDetail.intro" :tagStyle="vuex_parse_style"
						:domain="vuex_config.upload ? vuex_config.upload.cdnurl : ''" @linkTap="navigate"></u-parse>
				</view>
			</view>
			<view v-if="activeIndex === 1" class="chapter">
				<view class="items" v-for="(item,index) in chapterList" :key="index">
					<view class="title">{{item.name}}</view>
					<view v-for="(ite,idx) in item.video" :key="idx" 
					@click="playVideo(ite)"  :class="'c-video'+(videoId == ite.id ?' c-active':'')">
						<view class="v-left">
							<view class="v-title"><text>{{ite.name}}</text></view>
							<view class="v-view">
								<text>浏览量：{{ite.view_num}}</text>
								<text></text>
							</view>
						</view>
						<view v-if="ite.watchedtime" class="v-right">
							<text class="sk">已看完</text>
						</view>
						<view v-else class="v-right">
							<text v-if="ite.free_seconds>0" class="sk">试看</text>
							<image v-else src="../../static/lock.png" style="width: 48rpx;height:48rpx"></image>
						</view>
					</view>
				</view>
			</view>
			<view v-if="activeIndex === 2" class="comment">
				<view class="scy">
					<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" :show-scrollbar="true"
						@scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll">
						<view class="items" v-for="(item,index) in commentList" :key="index">
							<view class="c-left">
								<u-avatar size="100" shape="circle" :src="item.user.avatar" font-size="36"></u-avatar>
							</view>
							<view class="c-right">
								<view class="rnc">
									<text>{{item.user.nickname}}</text>
									<text class="sj">{{item.createtime_text}}</text>
								</view>
								<view class="plnr">
									{{item.content||''}}
								</view>
							</view>
						</view>
						<u-loadmore :status="has_more" fontSize="24" :line="true" />
					</scroll-view>
				</view>
			</view>


		</view>
		<view v-if="activeIndex === 2" class="pl-btn">
			<u-input placeholder="善语结善缘,恶言伤人心" border="surround" shape="circle" v-model="commentValue"
				:customStyle="{'background-color':'#e6e6e6'}" @confirm="sendComment"></u-input>
		</view>
		<u-modal :show="buyShow" :showCancelButton="true" confirmText="需要" cancelText="不需要" :title="title"
		 :content='content' @cancel="buyShow=false" @confirm="openTraining"></u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title:'提示',
				courseDetail: [],
				content:'你还未报名相关专业的培训，是否需要培训？',
				list1: [{
					name: "课程介绍"
				}, {
					name: '章节'
				}, {
					name: '评论（0）'
				}],
				activeIndex: 0,
				courseId: 0,
				chapterList: [],
				commentList: [],
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				commentValue: '',
				isCollect: false,
				page: 1,
				has_more: true,
				videoUrl: '',
				coverUrl: '',
				videoType: 'video',
				videoId: 0,
				lastSavedTime: 0,
				throttleInterval: 5000, // 节流间隔5秒
				currentTime:0,
				chapterIndex:0,
				freeSeconds:0,
				majorId:0,
				buyShow:false

			};
		},
		onLoad(e) {
			this.courseId = e.course_id
		},
		onShow() {
			this.getCourseDetail()
			this.getCourseChapter()
		},
		onReady: function(res) {
			// #ifndef MP-ALIPAY
			this.videoContext = uni.createVideoContext('myVideo')
			// #endif
		},
		methods: {
			buyClose(){},
			buyOpen(){},
			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				if (this.has_more) {
					this.page += 1;
					this.getCourseComments();
				}
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				// 解决view层不同步的问题
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			//点击播放
			playVideo(item) {
				if(item.free_seconds>0){
					this.freeSeconds = item.free_seconds
				}else{
					if (!this.vuex_token) {
						uni.$u.route('/pages/login/mobilelogin');
						return;
					}
					if(!item.is_watch) return;
				}
				this.videoType = item.type
				this.videoId = item.id
				if (item.type == 'video') {
					this.videoUrl = item.video_url
				} else {
					this.videoUrl = ''
					this.openField(item.video_url)
				}
				this.coverUrl = item.cover_url
				this.videoContext.play();
			},
			click() {},
			clickTabs(index) {
				this.activeIndex = index

				if (index === 2) {
					this.page = 1
					// this.has_more = true
					this.getCourseComments()
				}
			},
			//详情
			getCourseDetail() {
				this.$api.getCourseDetail({
					params: {
						course_id: this.courseId
					}
				}).then((res) => {
					if (res.code) {
						this.courseDetail = res.data;
					} else {
						uni.$u.toast(res.msg);
					}
				})
			},
			//章节
			getCourseChapter() {
				this.$api.getCourseChapter({
					params: {
						course_id: this.courseId
					}
				}).then((res) => {
					if (res.code) {
						this.chapterList = res.data
						this.videoType = this.chapterList[0].video[0].type
						this.videoId = this.chapterList[0].video[0].id
						this.freeSeconds = this.chapterList[0].video[0].free_seconds
						this.videoUrl = this.chapterList[0].video[0].video_url
						this.coverUrl = this.chapterList[0].video[0].cover_url
					} else {
						uni.$u.toast(res.msg);
					}
				})
			},
			//评论列表
			getCourseComments() {
				this.$api.getCommentList({
					params: {
						course_id: this.courseId,
						page: this.page
					}
				}).then((res) => {
					if (res.code) {
						if (this.page === 1) {
							this.commentList = [];
						}
						let pageList = res.data
						let commentList = res.data.data
						this.has_more = pageList.current_page < pageList.last_page;
						this.commentList = [...this.commentList, ...commentList];
					}
				})
			},
			//发送评论
			sendComment() {
				this.$api.sendComment({
					content: this.commentValue,
					course_id: this.courseId
				}).then((res) => {
					if (res.code) {
						this.commentValue = '';
						this.page = 1;
						this.getCourseComments()
					} else {
						uni.$u.toast(res.msg);
					}
				})

			},
			//收藏/取消收藏
			collect() {
				this.$api.postCollect({
					course_id: this.courseId
				}).then((res) => {
					if (res.code) {
						this.courseDetail.is_collect = res.data.is_collect
					}
					uni.$u.toast(res.msg);

				})
			},
			//打开文件
			openField(fileUrl) {
				let that = this
				uni.downloadFile({
					url: fileUrl, //自定义的文件地址
					filePath: '', //设置文件名
					success: function(res) {
						var filePath = res.filePath || res.tempFilePath;
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function(res) {
								//记录学习和浏览量
								that.$api.watchCourseVideo({course_id:that.courseId,video_id:that.videoId,time:0}).then((res)=>{
									
								})
							},
							fail(res) {
								console.log(res)
							}
						});
					}
				});
			},
			openTraining(){
				//跳转培训报名
				uni.$u.route({
					url: '/pages/training/training',
					params: {
						major_id: this.courseDetail.major_id
					}
				});
				return ;
			},
			// 恢复播放进度
			handleLoadedMetadata() {
				const savedTime = uni.getStorageSync(`videoProgress_${this.videoId}`) || 0;
				// uni.createVideoContext('myVideo')
				this.videoContext.seek(savedTime); // 使用seek方法跳转进度
			},

			// 时间更新监听（自动节流）
			handleTimeUpdate(e) {
				const currentTime = e.detail.currentTime;
				// console.log(this.freeSeconds,currentTime)
				if(this.freeSeconds<=currentTime){
					this.videoContext.stop()
					if (!this.vuex_token) {
						uni.$u.route('/pages/login/mobilelogin');
						return;
					}else{
						
						this.buyShow = true
						return;
					}
					return;
				}
				this.currentTime = currentTime
				const now = Date.now();

				// 手动节流逻辑
				if (now - this.lastSavedTime > this.throttleInterval) {
					this.saveProgress(currentTime);
					this.lastSavedTime = now;
				}
			},

			// 暂停事件
			handlePause(e) {
				this.saveProgress(this.currentTime);
			},
			// 保存进度方法
			saveProgress(time) {
				try {
					// 本地存储
					uni.setStorageSync(`videoProgress_${this.videoId}`, time);

					// 服务端同步（可选）
					// console.log('freeSeconds',this.freeSeconds)
					if(this.freeSeconds==0){
						this.syncToServer(time);
					}
				} catch (err) {
					console.error('存储进度失败:', err);
				}
			},

			// 同步到服务端（示例）
			async syncToServer(time) {
				try {
					let res = await this.$api.watchCourseVideo({
						type:'video',
						course_id:this.courseId,
						video_id:this.videoId,
						time:time
					})
				} catch (err) {
					console.error('同步进度失败:', err);
				}
			}


		},
		// 生命周期：页面卸载/隐藏时保存
		onUnload() {
			const currentTime = this.currentTime;
			this.saveProgress(currentTime);
		},
		onHide() {
			const currentTime = this.currentTime;
			this.saveProgress(currentTime);
		}

	}
</script>

<style lang="scss" scoped>
	.content {
		background-color: #F3F5F8;
		padding: 188rpx 24rpx 0rpx;
	}

	.video-play {
		width: 100%;
		height: 395rpx;
		border-radius: 20rpx;

		.video {
			width: 100%;
			height: 100%;
			border-radius: 20rpx;
		}

		.no-video {
			position: relative;
		}

		.play {
			position: absolute;
			left: 50%; //起始是在body中，横向距左50%的位置
			top: 50%; //起始是在body中，纵向距上50%的位置，这个点相当于body的中心点，div的左上角的定位
			transform: translate(-50%, -50%);
		}
	}

	.ft30 {
		font-size: 30rpx;
	}

	.ft28 {
		font-size: 28rpx;
	}

	.fw6 {
		font-weight: 600;
	}

	.tabs {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx 57rpx;

		.it {
			text-align: center;

		}

		/deep/ .u-line {
			border-bottom-width: 10rpx !important;
			margin: 20rpx auto !important;
		}
	}


	.detail {
		background-color: #ffffff;
		padding: 34rpx 24rpx;
		border-radius: 20rpx;

		.detail1 {
			padding: 24rpx 0;

			.major {
				background-color: #FF6905;
				border-radius: 10rpx;
				color: #ffffff;
				font-size: 24rpx;
				padding: 4rpx 8rpx;
				margin-right: 16rpx;
			}

			.name {
				font-size: 32rpx;
				color: #000000;
				font-weight: 600;
			}
		}
	}

	.d-content {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.c-left {
			text {
				font-size: 24rpx;
				color: #999999;
			}
		}

		.c-right {
			display: flex;
			align-items: center;

			.like {
				margin-left: 10rpx;
				color: #666666;
				font-size: 24rpx;
			}
		}
	}

	.c-intro {
		margin-top: 24rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 32rpx 28rpx;
	}

	.chapter {
		.items {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 24rpx;

			.title {
				color: #000000;
				font-size: 30rpx;
				font-weight: 600;
			}

			.c-video {
				display: flex;
				align-items: center;
				justify-content: space-between;
				background-color: #F3F5F8;
				padding: 24rpx;
				margin-top: 24rpx;
				border-radius: 10rpx;

				.v-left {
					.v-title {
						font-size: 30rpx;
						color: #333333;
						font-weight: 600;
						margin-bottom: 16rpx;
						width: 448rpx;
					}

					.v-view {
						font-size: 24rpx;
						color: #999999;
					}
				}
				.v-watched{
					text{
						color: #47A467;
					}
				}
				.v-right {
					.sk {
						background-color: #D0F0DB;
						color: #47A467;
						font-size: 24rpx;
						padding: 6rpx 12rpx;
						border-radius: 4rpx;
					}
				}
			}
			.c-active{
				background-color: #E2EDFF;
				border: 1rpx solid #0052D9;
			}
		}
	}

	.comment {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 24rpx;

		.scy {
			height: 770rpx;
			overflow: hidden;
			padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
			padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		}

		.scroll-Y {
			height: 100%;
		}

		.items {
			padding: 16rpx 8rpx;
			display: flex;

			.c-left {
				margin-right: 24rpx;
			}

			.c-right {
				width: 100%;

				.rnc {
					display: flex;
					align-items: center;
					justify-content: space-between;

					text {
						color: #666666;
						font-size: 28rpx;
					}

					.sj {
						font-size: 24rpx !important;
					}
				}

				.plnr {
					margin-top: 16rpx;
					color: #333333;
					font-size: 28rpx;
				}
			}
		}
	}

	.pl-btn {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #ffffff;
		padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	}
</style>